package com.rayo.accesscontrollercopy.module.setting;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.rayo.accesscontrollercopy.R;
import com.rayo.accesscontrollercopy.app.BaseFragment;
import com.rayo.accesscontrollercopy.model.db.bean.KeyData;
import com.rayo.accesscontrollercopy.model.db.dao.CurrentUserDao;
import com.rayo.accesscontrollercopy.model.db.dao.CurrentUserImpl;
import com.rayo.accesscontrollercopy.model.db.dao.KeyDataDao;
import com.rayo.accesscontrollercopy.model.db.dao.KeyDataImp;
import com.rayo.accesscontrollercopy.module.adapter.KeyAdapter;
import com.rayo.accesscontrollercopy.module.adapter.OnClicker;
import com.rayo.accesscontrollercopy.module.user.UserActivity;
import com.rayo.accesscontrollercopy.utils.CancelUtils;
import com.rayo.keyholder.data.KeyHolderData;

import java.util.HashMap;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * Created by lyc-pc on 17/2/23.
 */

public class KeyFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    private RecyclerView mRlvFragmentKey;

    private SwipeRefreshLayout mSrlFragmentKey;



    private HashMap<Integer, KeyData> mHashMap;
    private KeyAdapter mAdapter;
    private GridLayoutManager mGridLayoutManager;
    private KeyDataDao mKeyDataDao = new KeyDataImp();
    private CurrentUserDao mCurrentUserDao = new CurrentUserImpl();
    private Dialog mDialog;
    private String[] mStrings = new String[2];
    private int check = 0;
    private Subscription mSubscription, mSubscription2;
    private static final int CREATE = 1;
    private static final int UNBIND = 2;
    private int keyBoxId = 1;
    private  List<KeyData> keyDataList;
    KeyDataDao keyDataDao = new KeyDataImp();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_key;
    }

    @Override
    protected void setupViews() {
        mRlvFragmentKey = (RecyclerView) rootView.findViewById(R.id.rlv_fragment_key);
        mSrlFragmentKey = (SwipeRefreshLayout) rootView.findViewById(R.id.srl_fragment_key);
    }

    @Override
    protected void initialized() {

        keyDataList = keyDataDao.getAll();
        if (keyDataList.size()==0){
            KeyData keyData=null;
            for (int i=0;i<16;i++){
                keyData=new KeyData();
                keyData.setAddress(i+1);
                keyData.setKeybox(2);
                keyData.setType(11);
                keyDataList.add(keyData);
                keyDataDao.addKeyData(keyData);
            }
        }
        mAdapter = new KeyAdapter(keyDataList, getContext());
        mGridLayoutManager = new GridLayoutManager(getContext(), 8);
        mRlvFragmentKey.setLayoutManager(mGridLayoutManager);
        mRlvFragmentKey.setAdapter(mAdapter);
        mSrlFragmentKey.setOnRefreshListener(this);

        mAdapter.setOnClicker(new OnClicker() {
            @Override
            public void click(View v, final int pos) {
                if (keyDataList.get(pos).getState()==0) {
                    Intent intent = new Intent(getActivity(), BindKeyActivity.class);
                    intent.putExtra("data", keyDataList.get(pos));
                    startActivityForResult(intent,1);
                }else {
                    StringBuffer stringBuffer = new StringBuffer();
                    stringBuffer.append(getString(R.string.bind_dialog_control_address,":")+keyDataList.get(pos).getAddress()+"\n");
                    stringBuffer.append(getString(R.string.bind_key_tagid,":")+keyDataList.get(pos).getTagid()+"\n");
                    stringBuffer.append(getString(R.string.bind_key_serial,":")+keyDataList.get(pos).getSerialnumber()+"\n");
                    stringBuffer.append(getString(R.string.bind_key_version,":")+keyDataList.get(pos).getVersion()+"\n");

                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle(getString(R.string.bind_details))
                            .setMessage(stringBuffer.toString())
                            .setPositiveButton(getString(R.string.unbind), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    keyDataList.get(pos).setState(0);
                                    keyDataList.get(pos).setVersion("");
                                    keyDataList.get(pos).setSerialnumber("");
                                    keyDataList.get(pos).setTagid("");
                                    keyDataDao.updateKeyData(keyDataList.get(pos));
                                    mAdapter.notifyDataSetChanged();
                                    dialog.dismiss();
                                }
                            })
                            .setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).create();
                    alertDialog.show();

                }
            }

            @Override
            public void onClick(View v, int pos, KeyData keyData) {

            }

            @Override
            public void longClick(View v, int pos) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
//            case R.id.fab_fragment_key:
//                Intent intent = new Intent(getContext(), SetKeyActivity.class);
//                intent.putExtra("keyboxid",keyBoxId);
//                startActivityForResult(intent, CREATE);
//                break;

        }
    }

    private void addDialog() {
        check = 0;
        mDialog = new AlertDialog.Builder(getContext()).setSingleChoiceItems(mStrings, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                check = which;

            }
        }).setPositiveButton(getString(R.string.okay), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (check == 0) {
                    Intent intent = new Intent(getContext(), SetKeyActivity.class);
                    startActivityForResult(intent, CREATE);
                } else {
                    Intent intent = new Intent(getContext(), UserActivity.class);
                    startActivityForResult(intent, UNBIND);
                }
            }
        }).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        }).create();
        mDialog.show();
    }

    @Override
    public void onRefresh() {
        addItem(keyBoxId);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        CancelUtils.unsubscribe(mSubscription);
        CancelUtils.unsubscribe(mSubscription2);
    }

    private void addItem(final int id ) {
//        if (!mSrlFragmentKey.isRefreshing())
//            mSrlFragmentKey.setRefreshing(true);



        CancelUtils. unsubscribe(mSubscription);
        mSubscription = Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                List<KeyData> list =  mKeyDataDao.getKeyDataByKeyBoxId(id);
                mHashMap.clear();
                for (int i = 0; i < 16; i++) {
                    mHashMap.put(i + 1, null);
                }
                if (list!=null){
                    for (int i = 0, len = list.size(); i < len; i++) {
                        mHashMap.put(list.get(i).getAddress(), list.get(i));
                    }
                }else {
                    for (int i = 0; i < 16; i++) {
                        mHashMap.put(i + 1, null);
                    }
                }

                Log.e("dddddd", mHashMap.size() + "");
                subscriber.onNext("");
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onNext(String s) {
                mAdapter.notifyDataSetChanged();
                mSrlFragmentKey.setRefreshing(false);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            keyDataList = keyDataDao.getAll();
            mAdapter.notifyDataSetChanged();
//            addItem(keyBoxId);
        }
    }
}
